import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { AlertController, ModalController, NavParams } from '@ionic/angular';
import { pb } from 'src/pb';
import { dialogConfirm } from '../components/dialog';
import { formSetValues } from '../components/formSetValues';
import { HttpService } from '../http.service';
import { charsets } from './mysql';

@Component({
  selector: 'app-conn',
  templateUrl: './conn.page.html',
  styleUrls: ['./conn.page.scss'],
})
export class ConnPage implements OnInit {
  form = this.fb.group({
    name: [
      '',
      [Validators.required, Validators.minLength(2), Validators.maxLength(20)],
    ],
    address: [
      '',
      [Validators.required, Validators.minLength(3), Validators.maxLength(50)],
    ],
    username: [
      '',
      [Validators.required, Validators.minLength(2), Validators.maxLength(20)],
    ],
    password: [
      '',
      [Validators.required, Validators.minLength(2), Validators.maxLength(20)],
    ],
    schema: [
      '',
      [Validators.required, Validators.minLength(2), Validators.maxLength(20)],
    ],
    charset: [
      '',
      [Validators.required, Validators.minLength(2), Validators.maxLength(20)],
    ],
  });
  conn: pb.IConn = {};
  charsets = charsets;
  constructor(
    params: NavParams,
    private fb: FormBuilder,
    private http: HttpService,
    private modalCtrl: ModalController,
    private alertCtrl: AlertController
  ) {
    this.conn = params.data.conn;
    formSetValues(this.form, this.conn);
  }

  ngOnInit() {}
  close() {
    return this.modalCtrl.dismiss();
  }

  async del(id: number) {
    if (
      await dialogConfirm(this.alertCtrl, {
        header: '删除',
        subHeader: `是否确定删除 [ ${this.conn.name} ] ?`,
      })
    ) {
      await this.modalCtrl.dismiss(await this.http.del(`/api/conn/${id}`));
    }
  }

  async onSubmit() {
    Object.assign(this.conn, this.form.value);
    if (this.conn.id) {
      await this.modalCtrl.dismiss(
        await this.http.put(`/api/conn/${this.conn.id}`, this.conn)
      );
      return;
    }
    await this.modalCtrl.dismiss(await this.http.post('/api/conn', this.conn));
  }
}
